package com.woniu.controller.config.init;


import com.woniu.model.mallSystem.entity.Commodity;
import com.woniu.model.mallSystem.gh.common.RedisConstant;
import com.woniu.model.gh.common.es.CommodityRepository;
import com.woniu.service.mallSystem.ICommodityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;

//@Component
public class InitCommodityRunner implements CommandLineRunner {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ICommodityService commodityService;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Autowired
    private CommodityRepository commodityRepository;

    @Override
    public void run(String... args) throws Exception {
        // 查询所有商品
        List<Commodity> commodityList = commodityService.list();

        // 数据同步到es的索引库
        //  elasticsearchRestTemplate.save(commodityList);
        commodityRepository.saveAll(commodityList);

        // 遍历商品，加入到Redis的zset集合，Sequence作为展示分值
        commodityList.forEach(commodity -> {
            redisTemplate.opsForZSet().add(RedisConstant.COMMODITY_LIST, commodity, commodity.getSequence());

        });
    }
}
